package com.amon.amonplayer;

import android.content.Context;
import android.os.Looper;

import java.util.concurrent.ExecutionException;

public class MainInit<T> {

    private final ObjectProvider<T> mProvider;

    private T mValue;

    public MainInit(ObjectProvider<T> provider) {
        mProvider = provider;
    }

    public T get(Context context) {
        if (mValue == null) {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                mValue = mProvider.get(context.getApplicationContext());
            } else {
                try {
                    mValue = Executor.MAIN_EXECUTOR.submit(() -> get(context)).get();
                } catch (ExecutionException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return mValue;
    }

    public interface ObjectProvider<T> {
        T get(Context context);
    }
}
